package com.boot.poi.util;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

public class TFileUtils {
    /**
     * 下载文件
     *
     * @param filePath
     * @param response
     * @param fileName
     */
    public static void downFile(String filePath, HttpServletResponse response, String fileName) {
        downFile(new File(filePath), response, fileName);
    }

    public static void downFile(File file, HttpServletResponse response, String fileName) {
        try {
            downFile(new FileInputStream(file), response, fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }

    public static void downFile(FileInputStream fis, HttpServletResponse response, String fileName) {
        try {
            response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
            BufferedInputStream bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 预防一手乱码
     *
     * @param workbook
     * @param codedFileName
     * @param response
     */
    public static void downExcelFile(Workbook workbook, String codedFileName, HttpServletResponse response) {
        if (workbook instanceof HSSFWorkbook) {
            codedFileName = codedFileName + ".xls";
        } else {
            codedFileName = codedFileName + ".xlsx";
        }

        try {
            codedFileName = new String(codedFileName.getBytes("UTF-8"), "ISO-8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        out(workbook, codedFileName, response);
    }

    private static void out(Workbook workbook, String codedFileName, HttpServletResponse response) {
        response.setHeader("content-disposition", "attachment;filename=" + codedFileName);
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
